from django.shortcuts import render, HttpResponse
from django.http import HttpResponseRedirect
from PythonDjangoWeb.models import Author, Article


# Create your views here.

def index(request):
    return HttpResponse("blog")


def authors(request):
    author_list = Author.objects.all()
    return render(request, 'author_list.html', {'author_list': author_list})


def articles(request):
    article_list = Article.objects.all()
    return render(request, 'article_list.html', {'article_list': article_list})


def article(request):
    tid = request.GET.get('id')
    article_model = Article.objects.get(id=tid)
    return render(request, 'article.html', {'article': article_model})


def article_update(request):
    tid = request.POST.get('id')
    article_model = Article.objects.get(id=tid)
    if 'title' in request.POST:
        article_model.title = request.POST.get('title')
    if 'content' in request.POST:
        article_model.content = request.POST.get('content')
    article_model.save()
    return HttpResponseRedirect('/blog/articles')


def article_delete(request):
    tid = request.GET.get('id')
    article_model = Article.objects.get(id=tid)
    article_model.delete()
    return HttpResponseRedirect("/blog/articles")
